package com.webframe.web.controller;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.webframe.constant.WFConstant;
import com.webframe.po.FileBean;
import com.webframe.security.WebPlatformUser;
import com.webframe.service.def.IHouseInfoRentPubService;
import com.webframe.service.def.ITableOperationService;
import com.webframe.util.MyFileUtils;
import com.webframe.util.UUIDGenerator;

@Controller
@RequestMapping("/houseInfoRentPub")
public class HouseInfoRentPubController extends BaseController
{
	private static final String ROOT = "upload\\houseImage\\";//文件上传默认路径相对于webContent
	@Autowired
	IHouseInfoRentPubService houseInfoRentService;
	@Autowired
	ITableOperationService tableOperationService;
	@RequestMapping
	public String index(HttpServletRequest request,HttpServletResponse response) throws Exception
	{
		String pid = request.getParameter("cityId");
		//区域数据
		StringBuffer districtStr = new StringBuffer();
		//房型数据
		String residenceTypeStr = "";
		//装修类型数据
		String adornTypeStr = "";
		//朝向数据
		String directionStr = "";
		//房屋配置数据
		StringBuffer houseConfigStr = new StringBuffer();
		//租金支付方式数据
		String rentPayTypeStr = "";
		
		List<Map<String, Object>> districtList = houseInfoRentService.getDistrict(pid);
		for (Iterator<Map<String, Object>> iterator = districtList.iterator(); iterator.hasNext();)
		{
			Map<String, Object> map = (Map<String, Object>) iterator.next();
			districtStr.append("<option value=\""+map.get("id_")+"\">"+map.get("name_")+"</option>");
		}
		List<Map<String, Object>> residenceTypeList = houseInfoRentService.getResidenceType(null);
		residenceTypeStr = listToStr(residenceTypeList);
		List<Map<String, Object>> adornTypeList = houseInfoRentService.getAdornType(null);
		adornTypeStr = listToStr(adornTypeList);
		List<Map<String, Object>> directionList = houseInfoRentService.getDirection(null);
		directionStr = listToStr(directionList);
		List<Map<String, Object>> houseConfigList = houseInfoRentService.getHouseConfig(null);
		for (Iterator<Map<String, Object>> iterator = houseConfigList.iterator(); iterator.hasNext();)
		{
			Map<String, Object> map = (Map<String, Object>) iterator.next();
			houseConfigStr.append("<input name=\"peizhi\" type=\"checkbox\" value=\"" + map.get("id_") + "\" /><label>" + map.get("name_") + "</label>");
		}
		List<Map<String, Object>> payTypeList = houseInfoRentService.getPayType(null);
		rentPayTypeStr = listToStr(payTypeList);
		request.setAttribute("districtStr", districtStr.toString());
		request.setAttribute("residenceTypeStr", residenceTypeStr);
		request.setAttribute("adornTypeStr", adornTypeStr);
		request.setAttribute("directionStr", directionStr);
		request.setAttribute("houseConfigStr", houseConfigStr.toString());
		request.setAttribute("rentPayTypeStr", rentPayTypeStr);
		return "/realEstate/addHouseRent";
	}
	
	/**
	 * 根据区域id获取所属商圈数据
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getBusinessArea")
	public String getBusinessArea(HttpServletRequest request,HttpServletResponse response) throws Exception
	{
		String pid = request.getParameter("id");
		//商圈数据
		StringBuffer businessAreaStr = new StringBuffer();
		if(StringUtils.isNotEmpty(pid))
		{
			List<Map<String, Object>> businessAreaList = houseInfoRentService.getDistrict(pid);
			for (Iterator<Map<String, Object>> iterator = businessAreaList.iterator(); iterator.hasNext();)
			{
				Map<String, Object> map = (Map<String, Object>) iterator.next();
				businessAreaStr.append("<option value=\""+map.get("id_")+"\">"+map.get("name_")+"</option>");
			}
		}
		outWrite(response, businessAreaStr.toString());
		return null;
	}
	/**
	 * 添加租房房源信息
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/addHouseRent")
	public String addHouseRent(HttpServletRequest request,HttpServletResponse response) throws Exception
	{
		String rentMode = request.getParameter("rent_mode");
		String districtId = request.getParameter("district_id");
		String streetId = request.getParameter("street_id");
		String xiaoqu = request.getParameter("xiaoqu");
		String xiaoquAddress = request.getParameter("xiaoqu_address");
		String bedroomNum = request.getParameter("huxing_shi");
		String familyroomNum = request.getParameter("huxing_ting");
		String bathroomNum = request.getParameter("huxing_wei");
		String area = request.getParameter("area");
		String floor = request.getParameter("ceng");
		String floorTotal = request.getParameter("ceng_total");
		String residenceTypeId = request.getParameter("fang_xing");
		String adornTypeId = request.getParameter("zhuangxiu");
		String directionId = request.getParameter("chaoxiang");
		String[] houseConfig = request.getParameterValues("peizhi");
		String houseConfigStr = "";
		if(houseConfig != null)
		{
			for (int i = 0; i < houseConfig.length; i++)
			{
				houseConfigStr += "".equals(houseConfigStr) ? houseConfig[i] : (","+houseConfig[i]);
			}
		}
		String rentPrice = request.getParameter("price");
		if("面议".equals(rentPrice))
		{
			rentPrice = "0";
		}
		String payTypeId = request.getParameter("pay_type");
		String title = request.getParameter("title");
		String description = request.getParameter("description");
		String images = request.getParameter("images");
		String phone = request.getParameter("phone");
		String person = request.getParameter("person");
		Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
		WebPlatformUser user = (WebPlatformUser)(currentUser.getPrincipal());
		String userId = user.getUserID();
		String id = UUIDGenerator.getUUID();
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id_", id);
		paramMap.put("rent_type_", rentMode);
		paramMap.put("district_id_", districtId);
		paramMap.put("business_area_id_", streetId);
		paramMap.put("community_name_", xiaoqu);
		paramMap.put("community_addr_", xiaoquAddress);
		paramMap.put("bedroom_num_", bedroomNum);
		paramMap.put("family_room_num_", familyroomNum);
		paramMap.put("bathroom_num_", bathroomNum);
		paramMap.put("area_", area);
		paramMap.put("floor_", floor);
		paramMap.put("floor_total_", floorTotal);
		paramMap.put("residence_type_id_", residenceTypeId);
		paramMap.put("adorn_type_id_", adornTypeId);
		paramMap.put("direction_id_", directionId);
		paramMap.put("house_config_", houseConfigStr);
		paramMap.put("rent_price_", rentPrice);
		paramMap.put("pay_type_id_", payTypeId);
		paramMap.put("title_", title);
		paramMap.put("description_", description);
		paramMap.put("image_name_", images);
		paramMap.put("telphone_", phone);
		paramMap.put("person_name_", person);
		paramMap.put("user_id_", userId);
		paramMap.put("status_", 0);
		paramMap.put("pub_time_", c);
		if(submissionPermission(request))
		{
			tableOperationService.doInsertExecute("t_house_info_rent_", paramMap);
		}
		return "redirect:/houseInfoRentPub.html";
	}
	/**
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getXiaoquData")
	public String getXiaoquData(HttpServletRequest request,HttpServletResponse response) throws Exception
	{
		String term = request.getParameter("term");
		String cityId = request.getParameter("cityId");
		if(StringUtils.isEmpty(term))
		{
			outWrite(response, "");
			return null;
		}
		List<Map<String, Object>> xiaoquList = houseInfoRentService.getXiaoqu(term, cityId);
		JSONArray jsonArray = JSONArray.fromObject(xiaoquList);
		outWrite(response, jsonArray.toString());
		return null;
	}
	private String listToStr(List<Map<String, Object>> list)
	{
		StringBuffer sb = new StringBuffer();
		for (Iterator<Map<String, Object>> iterator = list.iterator(); iterator.hasNext();)
		{
			Map<String, Object> map = (Map<String, Object>) iterator.next();
			sb.append("<a data=\"" + map.get("id_") + "\" href=\"javascript: void(0);\">" + map.get("name_") + "</a>");
		}
		return sb.toString();
	}
	
	/**
	 * 批量上传文件
	 * @param request
	 * @param response
	 * @param fileBean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uploadFiles")
	public ModelAndView uploadFiles(HttpServletRequest request, HttpServletResponse response,FileBean fileBean) throws Exception 
	{
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		rootPath += ROOT;
		String sp = rootPath + (fileBean.getPath() == null?"":fileBean.getPath());
		Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
		WebPlatformUser user = (WebPlatformUser)(currentUser.getPrincipal());
		String userId = user.getUserID();
		sp +=  "\\" + userId + "\\";
		MyFileUtils.mkDirectory(sp);
		Map<String, Object> map = MyFileUtils.upload(fileBean.getMyUploadFileName(), sp, fileBean.getMyUpload());
		String fileName = map.get("newFileName")==null?"":map.get("newFileName").toString();
		outWrite(response, "{success:"+map.get("flag")+",newFileName:\""+fileName+"\"}");
		return null;
	}
	/**
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteImage")
	public String deleteImage(HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		String userId = request.getParameter("userId");
		String fileName = request.getParameter("fileName");
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		rootPath += ROOT;
		String fullPath = rootPath + "\\" + userId + "\\" + fileName;
		boolean success = MyFileUtils.delFile(fullPath);
		outWrite(response, "{success:" + success + "}");
		return null;
	}
	/**
	 * 判断重复提交
	 * @param request
	 * @return
	 */
	private boolean submissionPermission(HttpServletRequest request)
	{
		// 如果是Ajax请求，不处理重复提交
		if ("true".equalsIgnoreCase(request.getParameter(WFConstant.IS_AJAX_))) 
		{
			return true;
		}
		String key1 = request.getParameter(WFConstant.Constant_Duplicate_Submission_KEY_);
		String key2 = "";
		if (request.getSession().getAttribute(WFConstant.Constant_Duplicate_Submission_KEY_) != null)
		{
			key2 = request.getSession()
				.getAttribute(WFConstant.Constant_Duplicate_Submission_KEY_)
				.toString();
		}
		request.getSession().setAttribute(WFConstant.Constant_Duplicate_Submission_KEY_, UUIDGenerator.getUUID());
		return (key1.equals(key2));
	}
}
